package com.power200.android.service;

import android.util.Log;

import com.power200.android.bean.BackLog;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by liuming on 10/11/15.
 */
public class BackLogService {

    private FileService fileService = new FileService();

    private static final String Path = "/master-life-bls.dat";

    private BackLogService() {
    }

    private List<BackLog> backLogList = new ArrayList<BackLog>();

    public void init() {
        // read from local file
    }

    public void createBackLog(BackLog backLog) {
        // write file
        backLogList.add(backLog);
        File file = fileService.openFile(Path);
        try {
            OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(file,true));
            osw.write(backLog.toFileString() + "\n");
            osw.flush();
            osw.close();
        } catch (FileNotFoundException e) {
            Log.e("File", "FileNotFoundException", e);
        } catch (IOException e) {
            Log.e("File", "IOException", e);
        }

    }

    public List<BackLog> getBackLogs() {
        return backLogList;
    }

    public static BackLogService getInstance() {
        if (instance == null) {
            instance = new BackLogService();
            instance.initBacklogList();
        }
        return instance;
    }

    private void initBacklogList() {
        backLogList.clear();
        try {
            File file = fileService.openFile(Path);
            InputStreamReader isr = new InputStreamReader(new FileInputStream(file));
            BufferedReader bufferedReader = new BufferedReader(isr);
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                backLogList.add(BackLog.parseToFileString(line));
            }
        } catch (FileNotFoundException e) {
            Log.e("File", "FileNotFoundException", e);
        } catch (IOException e) {
            Log.e("File", "IOException", e);
        }
        Log.i("File","Init");
    }

    private static BackLogService instance = null;

}
